//-----------------------------------------------------------------------------
// File: PictureBoxShape.cs
//
// Copyright (c) Dmitry Shuklin. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using Microsoft.DirectX.Direct3D;

namespace ObjectiveDraw.Platform
{
	/// <summary>
	/// Summary description for PictureBoxShape.
	/// </summary>
	public class PictureBoxShape : SinglePointShapeBase
	{

		private int ImageWidth;
		private int ImageHeight;

		#region IDrawerShape Members

		
		public override float DistanceFrom(ObjectiveDraw.Platform.DrawerChartBase control, System.Drawing.PointF point)
		{
			float xo1 = OffsetFromAbscissa(control, PointAbscissa);
			float yo1 = OffsetFromOrdinate(control, PointOrdinate);

			double dx1 = point.X - xo1;
			double dy1 = point.Y - yo1;

			return (float)Math.Sqrt(dx1*dx1 + dy1*dy1);
		}


		public override void RenderShape(DrawerChartBase control, ChartInfoArgs cinfo, Cerebrum.Direct3D.Forms.RenderEventArgs re, float z)
		{
			base.RenderShape (control, cinfo, re, z);

			Microsoft.DirectX.Direct3D.Device device = re.Device;
			
			float x1 = OffsetFromAbscissa(control, PointAbscissa);

			float y1 = OffsetFromOrdinate(control, PointOrdinate);

			Texture _ImageTexture = Cerebrum.Direct3D.Drawing.Graphics.DeviceObjects[device, this] as Texture;

			if(_ImageTexture == null)
			{
				System.Drawing.Image image = null;
				Cerebrum.Integrator.DomainContext masterContext = ((Cerebrum.Integrator.Application)this.DomainContext.Application).MasterContext;
				Cerebrum.ObjectHandle h = Cerebrum.Management.Utilites.ResolveHandle(masterContext, "UiCommands", "Name", this.TypeName);
				if(!Cerebrum.ObjectHandle.Null.Equals(h))
					using(Cerebrum.Data.TableView view = Cerebrum.Management.Utilites.GetView(masterContext, "UiCommands"))
					{
						using(Cerebrum.IComposite connector = view.CreateItemViewByObjectHandle(h).GetComposite())
						{
							image = ((Cerebrum.Windows.Forms.Reflection.UiCommandDescriptor)connector.Component).GetNormalLeaveImage();
						}
					}
				ImageWidth = image.Width;
				ImageHeight = image.Height;
				_ImageTexture = Texture.FromBitmap(device, new System.Drawing.Bitmap(image), 0, Pool.Managed);
				Cerebrum.Direct3D.Drawing.Graphics.DeviceObjects[device, this] = _ImageTexture;
				image.Dispose();
			}

			System.Drawing.RectangleF rect = System.Drawing.RectangleF.Empty;
			rect.X = x1 - ImageWidth / 2;
			rect.Y = y1 - ImageHeight / 2;
			rect.Width = ImageWidth;
			rect.Height = ImageHeight;

			Cerebrum.Direct3D.Drawing.Graphics.FromDevice(device).DrawRectangle(rect ,z, _ImageTexture, System.Drawing.Color.White);

		}

		#endregion

		protected override void Dispose(bool disposing)
		{
			if(disposing)
			{
				Cerebrum.Direct3D.Drawing.Graphics.DeviceObjects.DisposeObject(this);
			}
			base.Dispose (disposing);
		}
	}
}
